<?php
/**
 *	产品服务类，供非管理模块使用。只提供非管理模块所需的方法。
 */
class ProductService extends Service {
	

	/**
	 * 通过上架商品id查询对应的商品名称
	 * @param array $ary_shelfid	一维数组
	 * @return	$result[shelf_id]=array("goods_title"=>*****)形式的数组
	 */
	public function select4UserPRelInfoByIds($ary_shelfid){
		$str_ids = implode(',',$ary_shelfid);
		$db_prefix = C('DB_PREFIX');
		$data = M('')->query("select g.title as 'goods_title',s.id as 'shelf_id' from {$db_prefix}goods g,{$db_prefix}goods_shelf s where s.id in ( {$str_ids} ) and g.id=s.goods_id ;");
		foreach($data as $vo){
			$result[$vo['shelf_id']]=array("goods_title"=>$vo['goods_title']);
		}
		return $result;
	}
	
	
	/**
	*	查询商品，通过查询条件查询。
	*	查询条件：参见search4Sys($map,$limit=16)方法。
	**/
	public function search4User($map,$limit=16){
		
		$map['partner_enable'] 	= 'Y';$map['goods_enable'] 		= 'Y';$map['shelf_enable'] 		= 'Y';
		$map['partner_is_delete'] = 'N';$map['goods_is_delete'] 	= 'N';$map['shelf_is_delete'] 	= 'N';
		
		return $this->search4Sys($map,$limit);
		return $pagedata;
	}
	
	
	/**
	*	查询商品，通过查询条件查询。
	*	查询条件：
	*					>按商户类别、id。
	*					>按商品类别、价格。
	*					>按主题选择。
	*	说明：
	*			>商户类别、id->查询partner表对应字段。
	*			>商品类别、价格->查询goods表对应字段。
	*			>主题选择->shelf表的sort_id字段。
	*			通过上述查询出基本信息后，查询价格信息。
	先查询出总的商户、商品、价格，对应关系表，然后依据enable字段判断是否可用，在通过价格表对照判断出
	**/
	public function search4Sys($map,$limit=16){
		if(!empty($map['sortcode']))
			$where['goods_sort_id']	=array('in',$map['sortcode']);
		
		if(!empty($map['shelf_id']))
			$where['shelf_id']	=$map['shelf_id'];
		
		if(!empty($map['p_sortcode']))
			$where['partner_sort_id']	=array('in',$map['p_sortcode']);
			
		if(!empty($map['brandid']))
			$where['partner_id']	=$map['brandid'];
		if(!empty($map['ary_brandid']))
			$where['partner_id']	=array('in',$map['ary_brandid']);
		
		
		if(!empty($map['gettype'])){
			if($map['gettype']=='self')$where['goods_get_type']	= array('NEQ',"delivery");
			if($map['gettype']=='delivery')$where['goods_get_type']	= array('NEQ',"self");
		}
				
		if(!empty($map['goods_id']))
			$where['goods_id']	=$map['goods_id'];
		
		if(!empty($map['sprice'])&&!empty($map['bprice'])){
			if(!empty($map['sprice']))
				$where['shelf_out_price']	=array('between',array($map['sprice'],$map['bprice']));
		}else{
			if(!empty($map['sprice']))
				$where['shelf_out_price']	=array('egt',$map['sprice']);
			if(!empty($map['bprice']))
				$where['shelf_out_price']	=array('elt',$map['bprice']);
		}
			
		$order='';//'sale' 'new' 'up' 'down'
		if($map['stype']=='sale')	$order=' stat_send_number desc ';
		if($map['stype']=='new'	)	$order=' shelf_on_time desc ';
		if($map['stype']=='up'	)	$order=' shelf_out_price asc ';
		if($map['stype']=='down')	$order=' shelf_out_price desc ';
		
		
		//货架状态对应的sql
		if(!empty($map['shelfstatus'])){
			if ($map['shelfstatus']=='on') {
				//未删除，全部有效，上架时间小于当前时间，下架时间大于当前时间。当前时间在商品有效期内，商品余额足
				$where['goods_enable']='Y';$where['partner_enable']='Y';$where['shelf_enable']='Y';
				$where['partner_is_delete']='N';$where['shelf_is_delete']='N';$where['goods_is_delete']='N';
				$where['shelf_off_time']	=array('GT',time());
				$where['shelf_on_time']		=array('LT',time());
				$where['shelf_off_time']	=array('GT',time());
				$where['shelf_on_time']		=array('LT',time());
			}
			if ($map['shelfstatus']=='off') {
				$where['goods_enable'] = array('EXP',"='N' OR `partner_enable`='N' OR `shelf_enable`='N' "
													."OR `partner_is_delete`='Y' OR `shelf_is_delete`='Y' OR `goods_is_delete`='Y' "
													."OR `shelf_off_time`<".time());
			}
			if ($map['shelfstatus']=='wait') {
				$where['goods_enable']='Y';$where['partner_enable']='Y';$where['shelf_enable']='Y';
				$where['partner_is_delete']='N';$where['shelf_is_delete']='N';$where['goods_is_delete']='N';
				$where['shelf_on_time']		=array('GT',time());
			}
		}else{
			if(in_array($map['partner_enable'],array('N','Y')))$where['partner_enable'] 	= $map['partner_enable'];
			if(in_array($map['goods_enable'],array('N','Y')))$where['goods_enable'] 	= $map['goods_enable'];
			if(in_array($map['shelf_enable'],array('N','Y')))$where['shelf_enable'] 	= $map['shelf_enable'];
			if(in_array($map['partner_is_delete'],array('N','Y')))$where['partner_is_delete'] 	= $map['partner_is_delete'];
			if(in_array($map['goods_is_delete'],array('N','Y')))$where['goods_is_delete'] 	= $map['goods_is_delete'];
			if(in_array($map['shelf_is_delete'],array('N','Y')))$where['shelf_is_delete'] 	= $map['shelf_is_delete'];
		}
		
		$shelfDao = M('ViewShelf');
		
		$pagedata = $shelfDao->kPageQuery($where,$order,$limit);
		//echo $shelfDao->getLastSql();
		
		return $pagedata;
	}
	
	
	/** 查询商品数据。查询指定条数。
	 * 
	 * @param unknown_type $where
	 * @param unknown_type $order
	 * @param unknown_type $limit
	 */
	public function selectByLimit($where,$order='',$limit=10){	
		$where['partner_enable'] 	= 'Y';$where['goods_enable'] 		= 'Y';$where['shelf_enable'] 		= 'Y';
		$where['partner_is_delete'] = 'N';$where['goods_is_delete'] 	= 'N';$where['shelf_is_delete'] 	= 'N';
		$shelflist = M('ViewShelf')->where($where)->order($order)->limit($limit)->findAll();
		return $shelflist;
	}
	
	/**
	 * 首页需要的产品数据，随机查询，查询出的数据按品牌分布。
	 * 如：要查询10个产品，10各品牌。则返回数据为每个品牌一个产品数据。
	 * @param 要查询的商品ID数组 $ary_bids
	 * @param 查询限制数量 $limit
	 */
	public function select4FirstPageProduct($ary_bids,$gettype,$limit){
		//dump($ary_bids);
		$no_brand = count($ary_bids);
		$hadPids;
		$products;
		for($i=0;$i<$limit;$i++){
			$where = null;
			$where['partner_id'] = $ary_bids[$i%$no_brand];
			if(!empty($hadPids))$where['shelf_id'] = array('not in',$hadPids);
			if($gettype=='self')$where['goods_get_type']	= array('EQ',"self");
			if($gettype=='delivery')$where['goods_get_type']	= array('EQ',"delivery");
			$_products = $this->selectByLimit($where,'shelf_send_number desc,shelf_default_number desc',1);
			//echo M('ViewShelf')->getLastSql();
			if(empty($_products)||count($_products)==0||count($_products[0])==0){
				//如果查询不存在则增加循环.设定一个种植循环条件
				if($no_brand*11>$limit)$limit++;
			}else{
				//dump($products);
				$products[$i] = $_products[0];
				$hadPids[]=$products[$i]['shelf_id'];
			}
		}
		return $products;
	}
	
	
	public function selectBrandId4User($map,$limit=10){
		$bids = D('Goods','Admin')->selectGoodsInfo($map,' distinct partner_id ',null,$limit,$ifpage=false);
		return $bids;
	}
	
	/**
	 * 通过上架ID查询上架商品商户信息。（查询不做过多条件，只是通过id查询）
	 * 查询出的数据，需要通过checkProductStatus()方法获得上架的进一步详细信息。
	 * @param String $shelfId
	 */
	public function getByShelfId($shelfId){
		$shelfDao = M('ViewShelf');
		$product = $shelfDao->where('shelf_id='.$shelfId)->find();
		
		//获取商户，额外说明信息。例如：配送范围，及相关说明保存于此。或兑换需注意事项。
		$explain = M('PartnerInfo')->where(array('partner_id'=>$product['partner_id']))->field('explain')->find();
		//echo M('PartnerInfo')->getLastSql();
		$product['partner_explain'] = $explain["explain"];
		return $product;
	}
	
	
	/**
	 * 检查上架商品状态.
	 *	返回格式：	result['isCanOn']	= true/false;//表示是否可以上架。
	 *				result['isWaiting']	= true/false;//表示是否等待上架。
	 *				result['p_status']	=	'Y'/'N'/'E'/'D';//对应表示商户 有效、无效、数据不存在、已删除。
	 *				result['g_status']	=	'Y'/'N'/'E'/'D';//对应表示商品 有效、无效、数据不存在、已删除。
	 *				result['s_status']	=	'Y'/'N'/'E'/'D';//对应表示上架 有效、无效、数据不存在、已删除。
	 *				result['desc']		=	'';//最终对上架商品当前是否可以上架或不可以上架的简单描述。
	 * @param unknown_type $product_data
	 */
	public function checkProductStatus($product_data){
		$result['isCanOn']	= false;
		$result['isWaiting']= false;
		$result['p_status']	=	'E';
		$result['g_status']	=	'E';
		$result['s_status']	=	'E';
		$result['desc']			=	'数据有误';
		$result['desc_more']=	'';
		if(empty($product_data))return $result;
			
		$result['s_status']	=	$this->_getStatus($product_data['shelf_id']
													,$product_data['shelf_enable'],$product_data['shelf_is_delete']);
		$result['g_status']	=	$this->_getStatus($product_data['goods_id']
													,$product_data['goods_enable'],$product_data['goods_is_delete']);
		$result['p_status']	=	$this->_getStatus($product_data['partner_id']
													,$product_data['partner_enable'],$product_data['partner_is_delete']);																																								
			
		$nowtime = time();
		//判断货架上的商品，商户，上架是否有效。
		if(!($result['s_status']=='Y'&&$result['g_status']=='Y'&&$result['p_status']=='Y')){
			$result['desc']	= '商品已暂停销售';
			if($result['g_status']=='Y'&&$result['p_status']=='Y'){
				if($result['s_status']=='N'){
					if($product_data['shelf_on_time'] > $nowtime){
						$result['isCanOn']	= false;
						$result['isWaiting']= true;
						$result['desc']		= '商品即将开始销售';
					}
				}
			}else{
						
			}
		}else{
			$result['isCanOn']	= true;
			$result['isWaiting']= false;
			$result['desc']		= '商品销售中';
			//如果下架时间小于当前时间，则自动下架。
			if($product_data['shelf_off_time'] < $nowtime){
				$result['isCanOn']	= false;
				$result['desc']			= '商品已暂停销售';
			}
			if($product_data['shelf_on_time'] > $nowtime){
				$result['isCanOn']	= false;
				$result['isWaiting']= true;
				$result['desc']			= '商品即将开始销售';
			}

			//上架商品总量与售出量对比
			if( $product_data['shelf_send_number'] >= $product_data['shelf_total_number'] ){
				$result['isCanOn']	= false;
				$result['isWaiting']= false;
				$result['desc']			= '商品已售完';
			}
					
			//统计出来的总量与售出量相等则说明已售完
			if( $product_data['stat_total_number'] <= $product_data['stat_send_number'] ){
				$result['isCanOn']	= false;
				$result['isWaiting']= false;
				$result['desc']			= '商品已售完';
			}
		}
		return $result;
	}
	
	/*
	*	内部使用的通过id，enable、is_delete获得对应的状态表示。
	*	返回数据为：'Y'/'N'/'E'/'D';//对应 有效、无效、数据不存在、已删除。
	*/
	private function _getStatus($id,$enable,$is_delete){
		if(empty($id))return 'E';
		if($is_delete!='N')return 'D';
		return $enable;
	}
	
	
	/** 取得商品的预定数量 ,暫時還沒有用到該方法。 **/
	public function getBookNum($shelf_id){
		$num = M('OrderBook')->where(' shelf_id='.$shelf_id)->field(' count(*) ')->find();
		return $num;
	}
	
	
	/**查询剩余量
	 * @param $goods_id
	 */
	public function getRemain($goods_id){
		if(empty($goods_id))return 0;
		$stat = M('ViewGoodsstat')->where("goods_id=".$goods_id)->find();
		//dump($stat);
		if(empty($stat))return 0;
		$tmp = $stat['stat_total_number']-$stat['stat_send_number'];
		if( $tmp < 1 )return 0;
		return $tmp;
	}

	
	/**
	 * 主要用于统计查询时，现获取制定的shelfid之用。
	 * @param array $map		包含：$pid--商户id   $gid--商品id
	 * @param String $order
	 * @param int $limit
	 */
	public function selectShelfIds4Sys($map,$order=null,$limit=null){
		$dao = M('ViewShelf');
		
		if(!empty($map['pid'])){
			if(is_array($map['pid'])){
				$where ['partner_id'] = array('in',$map['pid']);
			}else{
				$where ['partner_id'] = $map['pid'];
			}
		}
		if(!empty($map['gid'])){
			if(is_array($map['gid'])){
				$where ['goods_id'] = array('in',$map['gid']);
			}else{
				$where ['goods_id'] = $map['gid'];
			}
		}
		if(!empty($map['gsort']))$where['goods_sort_id']=$map['gsort'];
		if(!empty($map['psort']))$where['partner_sort_id']=$map['psort'];
		//$map['partner_enable'] 	= 'Y';$map['goods_enable'] 		= 'Y';$map['shelf_enable'] 		= 'Y';
		$where['partner_enable'] 	= 'Y';
		$where['partner_is_delete'] = 'N';//$map['goods_is_delete'] 	= 'N';$map['shelf_is_delete'] 	= 'N';
		//dump($where);
		$shelf_ids = $dao->where($where)->field("shelf_id")->order($order)->limit($limit)->findAll();
		//dump($dao->getLastSql());
		
		$shelf_ids=getSubByKey($shelf_ids,"shelf_id");
		
		return $shelf_ids;
	}
	
	//服务初始化
	public function init($data = '') {
	}
	
	//运行服务，系统服务自动运行
	public function run() {
	}
}
?>